package org.arch_learn.servlet_container.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {
    /**
     * 获取静态资源的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + "static" + path;
    }

    /**
     * 输出静态资源
     * @param fileInputStream
     * @param outputStream
     * @throws IOException
     */
    //符号"/"指向classes目录，不是一个具体文件
    public static void outPutResource(InputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = fileInputStream.available();
        }

        int resourceSize = count;
        //先输出http响应头，再输出具体内容
        outputStream.write(HttpProtocolUtil.getHttp200ResponseHeader(resourceSize).getBytes());

        //读取内容输出
        //已经读取的长度
        long written = 0;
        //计划一次性读取的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            //剩余未读大小小于1024byte时
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            fileInputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }
    }

}
